export const url = `ws://${location.hostname}:16672`
export class WebSocketClient {
  constructor() {
    this.url = url
    this.isClose = false
    this.reconnectInterval = 1000 * 15 // 重连间隔时间，单位毫秒
    this.connect()
  }

  connect() {
    this.socket = null
    this.socket = new WebSocket(this.url)

    this.socket.onopen = () => {
      this.onOpen()
    }

    this.socket.onmessage = (event) => {
      this.onMessage(event.data)
    }

    this.socket.onclose = (e) => {}

    this.socket.onerror = (error) => {
      this.onError(error)
      !this.isClose && this.reconnect()
    }
  }

  reconnect() {
    setTimeout(() => {
      this.connect()
    }, this.reconnectInterval)
  }

  onOpen() {
    // console.log('WebSocket连接已建立')
  }

  onMessage(message) {
    // console.log('收到消息：', message)
  }

  onClose() {
    this.isClose = true
    // console.log('WebSocket连接已关闭')
  }

  onError(error) {
    console.error('WebSocket发生错误：', error)
  }
}

export default function Socket({ success }) {
  let client = new WebSocketClient()

  client.onMessage = (message) => {
    success && success(JSON.parse(message))
    // console.log('收到消息：', message)
  }

  this.$once('hook:beforeDestroy', () => {
    client.onClose()
    client = null
  })

  return client
}
